/* 
用户管理的路由器
*/
const express = require("express");
const UserModel = require("../db/models/UserModel");
const md5 = require("md5");
const { RES_CODE } = require("../utils/contants");
const formidable = require('formidable')
const path = require('path')

// 创建路由器对象
const router = express.Router();

// 获取分页列表
router.get("/user/:page/:limit", async (req, res) => {
  // 获取参数
  const {page, limit} = req.params

  // 计算skip 
  const skip = limit * (page - 1)
  
  try{
    // 查询分页数据
    const users = await UserModel.find().skip(skip).limit(limit);
    
    const total = await UserModel.count()
    
    return res.json({
      code: RES_CODE.SUCCESS,
      data: {
        users,
        total
      },
      message: '获取列表成功',
    })
  }catch(e){
    console.log(e);
    return res.send({
      code: RES_CODE.SERVER_ERROR,
      message: "获取失败, 服务端异常",
    });
  }
});

// 获取单个用户
router.get("/user", async (req, res) => {
  // 获取 id 参数
  let { id } = req.query;
  try {
    // 获取用户信息
    let user = await UserModel.findById(id);
    return res.json({
      code: RES_CODE.SUCCESS,
      data: user,
      message: "获取用户成功",
    });
  } catch (e) {
    console.log(e);
    return res.send({
      code: RES_CODE.SERVER_ERROR,
      message: "获取用户失败, 服务端异常",
    });
  }
});

// 删除用户
router.delete("/user/:id", async (req, res) => {
  //获取 id 参数
  let { id } = req.params;

  try {
    //删除数据库中的数据
    await UserModel.deleteOne({ _id: id });
    return res.json({
      code: RES_CODE.SUCCESS,
      message: "删除成功",
    });
  } catch (e) {
    console.log(e);
    return res.send({
      code: RES_CODE.SERVER_ERROR,
      message: "添加失败, 服务端异常",
    });
  }
});

// 新增用户
router.post("/user", (req, res) => {
  // 创建处理带文件表单请求的对象
  const form = formidable({
    uploadDir: path.resolve(__dirname, "../public/upload"), // 保存的目录
    keepExtensions: true, // 生成的文件带扩展名  默认不带
  });

  form.parse(req, async (err, fields, files) => {
    if (err) {
      return res.json({
        code: RES_CODE.SERVER_ERROR,
        message: "图片上传失败",
      });
    }

    // 获取用户名和密码
    const {username, pwd} = fields
    // 判断数据否是有
    if (!username || !pwd) {
      return res.json({
        code: RES_CODE.DATA_ERROR,
        message: "用户名和密码是必须的",
      });
    }

    try {
      // 查询是否有该用户名的数据
      let user = await UserModel.findOne({ username });
      // 如果存在
      if (user) {
        return res.json({
          code: RES_CODE.DATA_ERROR,
          message: "该用户名已经存在",
        })
      }
      // 确定上传图书的访问路径
      const {profileFile} = files
      const filename = profileFile.newFilename
      const profile = '/upload/' + filename
      console.log(profile)
      //插入数据
      user = await UserModel.create({
        username,
        pwd: md5(pwd),
        profile,
      });

      // 返回
      return res.json({
        code: RES_CODE.SUCCESS,
        data: user,
        message: '添加成功'
      });
    } catch (e) {
      console.log(e);
      return res.send({
        code: RES_CODE.SERVER_ERROR,
        message: "添加失败, 服务端异常",
      });
    }  
  });
});

// 修改用户
router.put("/user", (req, res) => {
  // 创建处理带文件表单请求的对象
  const form = formidable({
    uploadDir: path.resolve(__dirname, "../public/upload"), // 保存的目录
    keepExtensions: true, // 生成的文件带扩展名  默认不带
  });
  form.parse(req, async (err, fields, files) => {
    if (err) {
      return res.json({
        code: RES_CODE.SERVER_ERROR,
        message: "图片上传失败",
      });
    }
    const {_id, username} = fields
    
    const {profileFile} = files
    const filename = profileFile.newFilename
    const profile = '/upload/' + filename
    try {
      await UserModel.updateOne({_id}, {username, profile})
      //响应成功
      return res.send({
        code: RES_CODE.SUCCESS,
        message: '更新成功'
      });
      
    } catch (e) {
      console.log(e.message);
      return res.send({
        code: RES_CODE.SERVER_ERROR,
        message: "更新失败, 服务端异常",
      });
    }
  })
});
 

module.exports = router;
